package com.oa.android.server;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.util.Log;
import android.view.WindowManager;

import com.google.gson.Gson;
import com.oa.android.MainActivity;
import com.oa.android.R;
import com.oa.android.activity.OnePiexlActivity;
import com.oa.android.activity.WelcomeActivity;
import com.oa.android.utils.MapLocationHelper;
import com.oa.android.utils.ServiceUtil;

/**
 * Created by zouqh on 2018/4/17.
 */

public class LocateService extends Service {

    private boolean isRun = false;
    private MapLocationHelper location;
    //    private SharedPreferencesHelper sp;
//    private WebSocket socket;
    private Gson mGson;


    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("LocateService----", "服务被启动了");
//        initData();
//        Notification notification = new Notification();
//        Intent intent = new Intent(this, MainActivity.class);
//        PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
//        notification.setLatestEventInfo(this, "智慧OA", "正在后台运行", pintent);
//        startForeground(1, notification);//设置最高级进程。 id 为 0状态栏的 notification 将不会显示
    }


    private Notification buildForegroundNotification() {
        Notification.Builder builder = new Notification.Builder(this);
        builder.setOngoing(true);
        builder.setContentTitle("OA正在运行").setContentText("正在定位中...").setSmallIcon(R.mipmap.app_img).setTicker("QQQ");
        builder.setPriority(Notification.PRIORITY_MAX);
        return builder.build();
    }

//    @Override
//    int onStartCommand(Intent intent, int flags, int startId) {
//        Log.e(TAG, "onStartCommand");
//        WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
//        mRootView = new FloatRootView(this);
//        mRootView.attach(windowManager);
//        mRootView.showBubble();
//        startForeground(1, buildForegroundNotification());
//        return START_STICKY;
//    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!isRun) {
            initData();
        }
        startForeground(1, buildForegroundNotification());
        return START_STICKY;
    }

    /**
     * 初始化数据
     */
    private void initData() {
        isRun = true;
        location = MapLocationHelper.getInstance();
//        if (!thread.isAlive()){
//            thread.start();
//        }
        TicketRunnable ticketRunnable = new TicketRunnable();
        new Thread(ticketRunnable).start();

    }


    class TicketRunnable implements Runnable {

        @Override
        public void run() {

            while (isRun) {
                //添加同步快
                synchronized (this) {

                    try {
                        Message msg = new Message();
                        msg.what = 1;
                        mHandler.sendMessage(msg);
                        Thread.sleep(3000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }


    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (isRun) {
                try {
                    Message msg = new Message();
                    msg.what = 1;
                    mHandler.sendMessage(msg);
                    Thread.sleep(3000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    });

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
//                    if (location.isLocation() == false) {
//                        location.startLocation();
//                    }
                    if (location == null) {
                        location = MapLocationHelper.getInstance();
                        location.startLocation();
                    }
                    if (null == location.mLocationClient) {
                        location.startLocation();
                    }
                    if (!location.mLocationClient.isStarted()) {
                        location.startLocation();
                    }
                    if (null == OnePiexlActivity.activity) {
                        checkScreen();
                    }
//                    if (null== MainActivity.mainActivity){
//                        checkScreen();
//                    }
                    Log.i("LocateService-----", "一直都还存活着");

//                    String longitude = String.valueOf(location.getLongitude());
//                    String latitude = String.valueOf(location.getLatitude());
//                    if (location.getLongitude() != 0.0 && location.getLatitude() != 0.0) {
//                        if (!sp.get("longitude", "").equals(longitude)
//                                || !sp.get("latitude", "").equals(latitude)) {
//
//                            sp.put("longitude", longitude);
//                            sp.put("latitude", latitude);
//
//                            String str = mGson.toJson(new Format(200,
//                                    new Locate(longitude, latitude)));
//                            socket.sendMessage(str);
//                        }
//                    }
                    break;
            }
        }
    };

    /**
     * 重启服务
     */
    private void restartService() {
        if (!ServiceUtil.isServiceRunning(this, ServiceUtil.SERVICE_NAME)) {
//            isRun = false;
            MapLocationHelper.getInstance().stopLocation();
//            WebSocket.getInstance().closeConnect();
//            SharedPreferencesHelper.getInstance().clear();
            Intent intent = new Intent(this, LocateService.class);
            this.startService(intent);
        }
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        restartService();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        restartService();
    }

    /**
     * 检查屏幕状态  isScreenOn为true  屏幕“亮”结束该Activity
     */
    private void checkScreen() {

        PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
        boolean isScreenOn = pm.isScreenOn();
        Log.i("isScreenOn---", "" + isScreenOn);
        if (!isScreenOn) {
            Intent it = new Intent(getApplicationContext(), OnePiexlActivity.class);
            it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(it);
//            Intent it = new Intent(getApplicationContext(), WelcomeActivity.class);
//            it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            startActivity(it);

        }
    }
}